import * as Cesium from 'cesium';

export class Collection {
  constructor(cesiumManager) {
    this.cesiumManager = cesiumManager;
  }

  /**
   * 添加实体到集合中
   * @param {Object} entity - 要添加的实体
   * @param {String} id - 实体ID（可选）
   * @returns {String} 实体ID
   */
  add(entity, id) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const viewer = this.cesiumManager.viewer;
    
    // 如果传入的是实体选项而不是实体本身，则创建新实体
    let entityToAdd;
    if (!(entity instanceof Cesium.Entity)) {
      entityToAdd = viewer.entities.add(entity);
    } else {
      entityToAdd = viewer.entities.add(entity);
    }
    
    return entityToAdd.id;
  }

  /**
   * 从集合中移除实体
   * @param {String|Entity} entityOrId - 实体或实体ID
   * @returns {Boolean} 是否成功移除
   */
  remove(entityOrId) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      return false;
    }

    const viewer = this.cesiumManager.viewer;
    
    if (typeof entityOrId === 'string') {
      return viewer.entities.removeById(entityOrId);
    } else {
      return viewer.entities.remove(entityOrId);
    }
  }

  /**
   * 根据ID获取实体
   * @param {String} id - 实体ID
   * @returns {Entity|undefined} 实体对象或undefined
   */
  getById(id) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      return undefined;
    }

    return this.cesiumManager.viewer.entities.getById(id);
  }

  /**
   * 获取所有实体
   * @returns {EntityCollection} 实体集合
   */
  getAll() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      return [];
    }

    return this.cesiumManager.viewer.entities.values;
  }

  /**
   * 根据条件筛选实体
   * @param {Function} predicate - 筛选条件函数
   * @returns {Array} 符合条件的实体数组
   */
  filter(predicate) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      return [];
    }

    return this.cesiumManager.viewer.entities.values.filter(predicate);
  }

  /**
   * 清空所有实体
   */
  clear() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      return;
    }

    this.cesiumManager.viewer.entities.removeAll();
  }

  /**
   * 批量添加实体
   * @param {Array} entities - 实体数组
   * @returns {Array} 添加的实体ID数组
   */
  addBatch(entities) {
    const ids = [];
    entities.forEach(entity => {
      ids.push(this.add(entity));
    });
    return ids;
  }

  /**
   * 获取实体数量
   * @returns {Number} 实体数量
   */
  getCount() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      return 0;
    }

    return this.cesiumManager.viewer.entities.values.length;
  }
}